package org.example.trigger.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.example.types.utils.ThreadLocalUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yinghuashen
 * @version 1.0
 * @description:
 * @date 2025/3/15 14:45
 */
@Slf4j
public class LoginInterceptorForTest implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor拦截器拦截请求");
        // 从请求头中获取userId、userName、userPhone
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        String userPhone = request.getHeader("userPhone");

        // 检查这些信息是否为空
        if (userId != null && userName != null && userPhone != null) {
            // 将用户信息存入ThreadLocal中，方便后续使用
            ThreadLocalUtils.addCurrentUser(userId, userName, userPhone);
        } else {
            // 处理用户信息缺失的情况，例如返回401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        log.info("清除用户信息");
        // 移除用户信息
        ThreadLocalUtils.removeUser();
    }


}
